package com.lee;

import javax.servlet.ServletException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;

public class User {
    int id;
    String username;

    public User(int id, String username) {
        this.id = id;
        this.username = username;
    }

    public static User insert(String username, String password) throws ServletException {
        //永远不要在数据库中保存用户的明文密码
        //1. 首先把password进行hash处理(这里使用sha256方法)  因为hash处理是单向的，所以就算数据库泄露，也无法使用密码
        password = encrypt(password);
        //2.利用JDBC保存MySQL
        try (Connection connection = DB.getConnection()) {
            String sql = "INSERT INTO users(username,password) VALUES(?,?)";
            try (PreparedStatement statement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS)) {
                statement.setString(1, username);
                statement.setString(2, password);

                statement.executeUpdate();
                //插入成功，获取插入后的自增id

                // 3.MySQL中的id是自增主键，所以，利用JDBC的方法取出id
                try (ResultSet resultSet = statement.getGeneratedKeys()) {
                    if (resultSet.next()) {
                        int id = resultSet.getInt(1);
                //4.返回构建好的用户对象
                        return new User(id, username);
                    }
                }
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
        //如果插入过程中出现问题 返回null
        return null;
    }

    //利用 SHA-256算法给密码做hash处理
    private static String encrypt(String password) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] input = password.getBytes("UTF-8");
            byte[] output = messageDigest.digest(input);

            StringBuilder sb = new StringBuilder();
            for (byte s : output) {
                sb.append(String.format("%02x", s));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return password;
        }
    }
}
